<template>
  <view class="shoppingBox">
    <view :style="showCartList ? 'z-index: 97' : ''" class="mask" v-if="showCartList || showCategoryBox" @click="closeMask"></view>
    <view class="shoppingBox_header" style="z-index: 93" :style="{ paddingTop: `${navbarHeight}px` }">
      <custom-navbar :immersive="true" title="社发配送" :showBack="false" color="#333"> </custom-navbar>
      <view class="shoppingBox_content_location" @click.prevent="goWarehouse">
        <view class="shoppingBox_content_location_icon"><image src="/static/image/loca_icon.png" mode="widthFix" /></view>
        <view class="shoppingBox_content_location_address">{{ warehouseInfo.name ? warehouseInfo.name : '未获取到定位' }}</view>
        <uni-icons type="right" size="16"></uni-icons>
      </view>
      <view style="position: relative">
        <locationDialog :showTip.sync="showTip"></locationDialog>
      </view>

      <uniSearchBar @input="queryCustomer" placeholder="请输入心仪的商品" bgColor="#fff" radius="50" :isFocus="false"></uniSearchBar>
      <view style="margin-top: 14rpx;">
        <categoryBox @setCategory="setCategory" @search="jump('searchGoods')" v-show="showCategoryBox" :typeList="goodsOneType" @close="showCategoryBox = false" :goodsTypeIndex="currentTypeIndex"></categoryBox>
      </view>

      <goodsTypeList @change="changeType" :goodsTypeIndex="goodsTypeIndex" @clickAll="showCategoryBox = true" :goods-types="goodsOneType"></goodsTypeList>
    </view>

    <view class="shoppingBox_content">
      <!-- <uni-search-bar @confirm="search" @input="input" cancelButton="none" placeholder="请输入心仪的商品"></uni-search-bar> -->
      <view class="shoppingBox_content_list">
        <view class="shoppingBox_content_list_left">
          <scroll-view :scroll-top="scrollTop" :style="{ height: contentHeight + 'px' }" scroll-y="true" class="scroll-Y">
            <type-menu :selectIndex.sync="currentTypeIndex" :types="subTypeList" @change="setGoodsType"></type-menu>
          </scroll-view>
        </view>
        <view class="shoppingBox_content_list_right">
          <view class="shoppingBox_content_list_right_type-name">{{subTypeList[currentTypeIndex].name}}</view>
          <!-- @refresherrefresh="refreshList"  :refresher-enabled="true"  :refresher-triggered="refreshing" -->
          <scroll-view @scrolltolower="queryData" :scroll-top="scrollTop" :style="{ height: contentHeight + 'px' }" scroll-y="true" class="scroll-Y">
            <goods-card @operateCount="operateCount" @selectGoods="selectGoods" @updateGoodCount="updateGoodCount" v-for="(item, index) in goodsList" :item="item" :index="index" @goDetail="goDetail"></goods-card>
            <view style="width: 100%; height: 210rpx" />
          </scroll-view>
        </view>
      </view>
    </view>

    <shopping-cart ref="shopCart" :selectKey="selectKey" :select-cart-list="selectCartList" @operateCount="operateCount" @triggerSelect="triggerSelect" @triggerSelectAll="triggerSelectAll" @clearCart="clearCart" @showCartPop="showCartPop" :showCartList="showCartList" @goDetail="goDetail" @jump="jump" @updateGoodCount="updateGoodCount"></shopping-cart>

    <uni-popup maskBackgroundColor="rgba(69,64,68,.6)" ref="popup" type="bottom" :animation="true">
      <goodDetail :item.sync="currentGoods" :index="currentIndex" @selectGoods="selectGoods" @closeDialog="closeMask" :customerId="customerId" @operateCount="operateCount"></goodDetail>
    </uni-popup>
  </view>
</template>

<script>
import Search from '@/components/search'
import { debounce, getScreen, getUserInfo } from '@/service/auth'
import typeMenu from '@/components/typeMenu'
import { basGoodsListForAdd, childBasGoodsTypeList, getBasGoodsBrandS } from '@/service/api/shopping'
import goodsCard from '@/components/goodsCard'
import goodsTypeList from '@/components/goodsTypeList'
import categoryBox from '@/components/categoryBox'
import goodDetail from '@/components/goodDetail'
import shoppingCart from '@/components/shoppingCart'

import stock from '@/components/stock'

import { getBasGoodsTypeTree } from '@/service/api/dropDown'
import proxyGoods from '@/utils/proxyGoods.js'
import navbarMixin from '@/mxins/navbar.js'
import { uniSearchBar } from '@/components/uniSearchBar.vue'
import { getBasWarehouseList } from '@/service/api/logistics'
import locationDialog from '@/components/location_dialog'
import { mapState, mapGetters, mapMutations } from 'vuex'
import { apiBaseUrl } from '@/service/config.js'
export default {
  name: 'shopping',
  mixins: [navbarMixin],
  components: { uniSearchBar, Search, typeMenu, goodsCard, goodsTypeList, goodDetail, shoppingCart, categoryBox, stock, locationDialog },

  data() {
    return {
      customerId: null,
      //一级分类指针
      goodsTypeIndex: 0,
      //末级分类指针
      currentTypeIndex: 0,
      //分类
      showCategoryBox: false,
      customerName: '请先选择客户',
      sCustomerId: null,
      scustomerId: null,
      scustomerName: '请先选择二批',
      contentHeight: 0,
      shoppingCartGoods: [],
      mask: false,
      typeList: [],
      goodsOneType: [],
      currentGoods: {},
      currentIndex: -1,
      goodsList: [],
      brandList: [],
      subTypeList: [],
      currentPromotionId: -1,
      end: false,
      query: {
        page: 1,
        size: 30,
        goodsTypeIds: '',
        type: 'SALE',
        isIgnoreZeroUnGiftGoodsCount: 1,
        isAppletSale: 1,
        scope: 0,
        ignoreGoodsTagNames: '回瓶回箱,瓶盖',
        keyword: '',
      },
      paths: {
        customer: '/pages/saleplace/index',
        searchGoods: '/pageShopping/search/index',
      },
      typeCallbackList: [],
      type: '',
      news: '',
      order: '',
      source: '',
      tabbar: null,
      photo: '',
      back: '',
      longitude: null,
      latitude: null,
      marker: [],
      warehouseInfo: {},
      user: {},
      selectKey: 'goodsId', //购物车商品选中key唯一字段
      selectCartList: [], //购物车选中的商品
      showCartList: false, //是否显示购物车列表
      showTip: false,
      goodType: {},
      orderSelectGoodList: [],
      refreshing: false,
    }
  },
  created() {
    const { width, height } = getScreen()
    this.contentHeight = height - (290 * width) / 750

    const app = getApp()

    const data = getUserInfo()
    this.user = JSON.parse(data)
    if (this.user) {
      this.customerId = this.user.customerIds
    }
    // console.log('cartItems', this.cartItems)
    // this.selectedGoodsList = this.cartItems || []
  },
  onLoad(option) {
    
  },
  onShow() {
    const app = getApp()

    const data = getUserInfo()
    this.user = JSON.parse(data)
    if (this.user) {
      this.customerId = this.user.customerIds
    }

    this.goodType = app.globalData.goodType //首页点击商品分类
    delete app.globalData.goodType

    this.getGoodsTypeOne()
    if (!this.warehouseInfo.id) {
      this.getLocation()
    }
  },
  computed: {
    ...mapState({
      cartItems: state => state.cart.cartItems,
    }),
    ...mapGetters(['totalPrice', 'totalGoodsCount']),
  },
  methods: {
    ...mapMutations('cart', ['updateGoodsCount', 'removeFromCart', 'toggleSelect', 'addToCart']),
    getBaseWareList() {
      const params = {
        page: 1,
        size: 100,
        lng: this.longitude,
        lat: this.latitude,
      }

      getBasWarehouseList(params).catch(err => {
        if (err.content.length > 0) {
          this.warehouseInfo = err.content[0]
        }
      })
    },
    getLocation() {
      const that = this
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        isHighAccuracy: true,
        success: function (res) {
          // that.showTip = false
          that.longitude = res.longitude
          that.latitude = res.latitude
          that.getBaseWareList() //获取自提点
          console.log('当前位置的经度：' + res.longitude)
          console.log('当前位置的纬度：' + res.latitude)
        },
        fail: function (err) {
          that.showTip = true
        },
      })
    },

    onGet: debounce(function () {
      uni.showLoading({ title: '加载中' })
      console.log('goodsTypeIds' + this.query.goodsTypeIds)
      if (!this.query.goodsTypeIds) return
      const data = {
        ...this.query,
      }
      if(this.customerId)data.customerId = this.customerId;
      basGoodsListForAdd(data).catch(err => {
        uni.hideLoading()
        console.log('err', err)
        if (err.status && err.status !== 200) {
          return this.uniShowToast(err.msg)
        }
        if (err.content.length < this.query.size) this.end = true

        err.content = err.content.map(item => {
          const index = this.cartItems.findIndex(val => val.goodsId === item.goodsId)
          return ~index ? this.cartItems[index] : { ...item, goodsCount: 0 }
        })

        this.goodsList = [...this.goodsList, ...err.content]
        this.refreshing = false
      })
    }, 300),
    jump() {
      const checkCartList = this.cartItems.filter(item => item.selected)
      if (!checkCartList.length) return uni.showToast({ title: '请先选择商品', icon: 'none' })

      try {
        //要从购物车列表中跳出选中的购物车数据

        uni.setStorageSync('cartList', checkCartList)
        uni.setStorageSync('wareInfo', this.warehouseInfo)

        this.closeMask()
        uni.navigateTo({ url: `/pageShopping/settlement/index` })
      } catch (e) {
        console.error('存储失败:', e)
      }
    },

    backs() {
      if (this.tabbar) {
        uni.switchTab({
          url: '/pages/home/index',
        })
      } else {
        uni.navigateBack()
      }
    },
    refreshList() {
      this.refreshing = true
      this.init()
      this.onGet()
    },
    init() {
      this.query.page = 1
      this.end = false
      this.goodsList = []
      // this.selectedGoodsList.length = 0
    },
    getGoodsTypeOne() {
      getBasGoodsTypeTree({ size: 999, sort: 'seq asc' }).catch(res => {
        this.goodsOneType = res
        this.goodsOneType.sort((a, b) => a.seq - b.seq)

        this.goodsOneType = this.goodsOneType.map(item => {
          return { ...item, imageUrl: this.isExternalLink(item.imageUrl) ? item.imageUrl : apiBaseUrl + item.imageUrl }
        })
        this.subTypeList = this.goodsOneType
console.log('goodtype',this.goodType)
        if (this.goodType) {
          const _index = this.goodsOneType.findIndex(item => item.id === this.goodType.id)

          if (~_index) {
            this.goodsTypeIndex = _index
            this.changeType(this.goodsOneType[_index])
          } else {
            this.goodsTypeIndex = 0
            this.changeType(res[0])
          }
        } else {
          this.goodsTypeIndex = 0
          this.changeType(res[0])
        }
      })
    },
    changeType(e) {
      console.log('changeType,e', e)

      this.getGoodsType(e.id)
    },
    // 获取第二分类
    getGoodsType(pid = '') {
      console.log('this.goodsTypeIndex', this.goodsTypeIndex)
      const _index = this.goodsOneType.findIndex(item => item.id === pid)
      if (~_index) {
        this.currentTypeIndex = _index
        this.query.goodsTypeIds = pid
      }

      this.init()
      this.onGet()
      // childBasGoodsTypeList({ pid: pid, size: 999 }).catch(err => {
      //   this.subTypeList = err.content
      //   const ids = `${pid},` + this.subTypeList.map(item => item.id).join(',')
      //   this.subTypeList.unshift({ id: ids, name: '全部' })
      //   this.currentTypeIndex = 0
      //   this.query.goodsTypeIds = ids
      //   this.init()
      //   this.onGet()
      // })
    },
    getGoodsTypeIds(goodsType) {
      let ids = ''
      if (goodsType.children && goodsType.children.length) {
        for (let tp of goodsType.children) {
          ids += this.getGoodsTypeIds(tp)
        }
      }
      return `${goodsType.id},${ids}`
    },
    setGoodsType(e) {
      console.log('setGoodsType', e)
      const _index = this.goodsOneType.findIndex(item => item.id === e.id)
      if (~_index) {
        this.goodsTypeIndex = _index
      }
      if (this.query.goodsBrandIds !== e.id) {
        this.query.goodsTypeIds = e.id
        this.init()
        this.onGet()
      }
    },
    queryData() {
      if (this.end) return
      this.query.page++
      this.onGet()
    },

    search(e) {
      // 查询
      this.query.keyword = e.value
      this.init()
      this.onGet()
    },
    queryCustomer(val) {
      this.query.keyword = val
      this.init()
      this.onGet()
    },
    showCartPop() {
      this.showCartList = !this.showCartList
    },

    triggerSelect(item) {
      // 购物车单品选中
      this.$store.commit('toggleSelect', item.goodsId)
    },
    triggerSelectAll(selectAll) {
      //全选
      this.$store.commit('triggerSelectAll', selectAll)
    },
    closeMask() {
      //蒙版隐藏
      this.showCartList = false
      this.$refs.popup.close()
    },
    clearCart() {
      // 清空购物车,数量要变成0
      uni.showModal({
        content: '确定要清空购物车',

        success: res => {
          if (res.confirm) {
            //删除
            this.$store.commit('clearCart')
            this.goodsList = this.goodsList.map(item => {
              return { ...item, goodsCount: 0 }
            })
          } else if (res.cancel) {
          }
        },
      })
    },
    selectGoods(item, goodsCount) {
      //加入购物车
      console.log('goodCount', goodsCount)
      const existingItem = this.goodsList.find(_item => _item.goodsId === item.goodsId)
      if (existingItem) {
        existingItem.goodsCount = goodsCount ? goodsCount : existingItem.goodsCount + 1
        this.$store.commit('addToCart', existingItem)
        this.uniShowToast('已加入购物车')
      }
    },
    updateGoodCount(item) {
      console.log('updateGoodCount', item.goodsCount)
      //直接更新购物车数量
      if (!item.goodsCount || (item.goodsCount && item.goodsCount <= 0)) {
        const existingItem = this.goodsList.find(_item => _item.goodsId === item.goodsId)
        console.log('shoping updateGoodCount', existingItem)
        if (existingItem) {
          existingItem.goodsCount = 1
        }
        this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: 1 })
      } else {
        this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: item.goodsCount })
      }
    },
    operateCount(params) {
      //购物车加减 from:是从购物车还是列表页返回
      console.log('index operateCount', params)
      const { item, type } = params
      const existingItem = this.goodsList.find(_item => _item.goodsId === item.goodsId)

      if (type === 'add') {
        const count = item.goodsCount + 1
        this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: count })
        if (existingItem) {
          existingItem.goodsCount = count
        }
      } else if (type === 'del') {
        if (item.goodsCount >= 2) {
          const count = item.goodsCount - 1
          this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: count })
          if (existingItem) {
            existingItem.goodsCount = count
          }
        } else {
          //弹框是否删除该商品
          uni.showModal({
            content: '确定要删除该商品么',

            success: res => {
              if (res.confirm) {
                //删除
                this.$store.commit('removeFromCart', item.goodsId)
                if (existingItem) {
                  existingItem.goodsCount = 0
                }
              } else if (res.cancel) {
              }
            },
          })
        }
      }
    },

    goDetail(param) {
      // this.$refs.popup.open()
      const { item, index } = param
      console.log('goDetail', item)
      const goodIndex = this.goodsList.findIndex(_item => _item.goodsId === item.goodsId)
      if (~goodIndex) {
        this.currentIndex = goodIndex
        this.currentGoods = item
        uni.navigateTo({ url: `/pageShopping/detail/index?index=${goodIndex}&item=` + encodeURIComponent(JSON.stringify(item)) })
      }
    },
    goWarehouse() {
      const _that = this
      uni.navigateTo({
        url: '/pageShopping/warehouse/index',
        events: {
          // 选择自提点，返回选中的自提点

          acceptDataFromOpenedPage: function (data) {
            console.log('back', data)
            if (data) {
              _that.warehouseInfo = data
            }
          },
        },
      })
    },
    goSetting() {
      wx.openSetting({
        success(res) {
          console.log('Setting opened:', res.authSetting)
          // 处理成功后的逻辑，比如用户是否授权了某些权限
        },
        fail(err) {
          console.error('Failed to open setting:', err)
        },
      })
    },
    setCategory(index) {
      this.goodsTypeIndex = index
      this.showCategoryBox = false
    },
  },
}
</script>

<style lang="scss" scoped>
.shoppingBox {
  background-color: #f6f6f6;
  height: 100vh;
  display: flex;
  flex-direction: column;
  &_header {
    z-index: 100;
    background: linear-gradient(to bottom, #c5f4ce 30%, #fff);
    padding-bottom: 20rpx;
  }
  &_content {
    flex: 1;
    overflow-y: auto;
    &_location {
      position: relative;
      display: flex;
      align-items: center;
      margin: 20rpx 20rpx 10rpx 20rpx;
      &_icon {
        width: 30rpx;
      }
      &_address {
        margin: 0 10rpx;
        font-size: 32rpx;
        font-weight: 500;
      }
    }
    &_list {
      display: flex;
      position: relative;
      overflow: hidden;
      /* padding-top: 20rpx; */
      z-index: 1;
      &_left {
        width: 200rpx;
        background: #f6f6f6;
      }
      &_right {
        flex: 1;
        background-color: white;
        &_type-name{
          margin: 20rpx;
          font-size: 32rpx;
          font-weight: bold;
        
        }
      }
    }
  }
  .headBackGround {
    width: 100%;
    position: absolute;
    top: 0;
    z-index: 0;
    image {
      width: 125%;
      margin-left: -13%;
    }
  }
  .head {
    position: relative;
    z-index: 1;
    .customer {
      color: #ffffff;
      font-size: 36rpx;
      font-weight: 600;
      font-family: PingFangSC;
      margin-top: 80rpx;
      padding-left: 50rpx;
      .down {
        height: 100%;
      }
    }
    .search {
      background-color: #ffffff;
      margin-top: 60rpx;
      height: 80rpx;
      width: 70%;
      border-radius: 80rpx;
      padding-left: 30rpx;
      input {
        height: 100%;
      }
    }
  }
}
.back {
  transform: rotate(90deg);
  width: 80rpx;
  height: 80rpx;
  margin-right: 50rpx;
}

.downImage {
  width: 50rpx;
  height: 50rpx;
}
.mask99 {
  z-index: 99;
}
.mask {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 90;
  background-color: rgba(0, 0, 0, 0.6);

  transition: all 0.3s ease;
}

</style>
